package com.mxw.component.security.aspectj;

import cn.hutool.core.text.CharSequenceUtil;
import com.mxw.commons.errorcode.GlobalErrorCode;
import com.mxw.commons.exception.CustomException;
import com.mxw.component.security.properties.CloudSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/** @Description "" @Author RingKo @Date 2022/11/11 17:41 @Version 1.0 */
@Aspect
@Component
@Slf4j
public class OnlyIntranetAccessAspect {
  @Resource private CloudSecurityProperties cloudSecurityProperties;

  @Pointcut("@within(com.mxw.component.security.annotation.OnlyIntranetAccess)")
  public void onlyIntranetAccessOnClass() {}

  @Pointcut("@annotation(com.mxw.component.security.annotation.OnlyIntranetAccess)")
  public void onlyIntranetAccessOnMethed() {}

  @Before(value = "onlyIntranetAccessOnMethed() || onlyIntranetAccessOnClass()")
  public void before(JoinPoint joinPoint) {
    HttpServletRequest hsr =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String token = hsr.getHeader(cloudSecurityProperties.getGatewayTokenHeader());
    if (CharSequenceUtil.isNotBlank(token)) {
      log.error("内部接口，拒绝访问！Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
      throw new CustomException(GlobalErrorCode.ILLEGAL_REQUEST);
    }
  }
}
